package cn.xiangxu.telecom.login.dao;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.annotation.Resource;
import javax.management.RuntimeErrorException;
import javax.sql.DataSource;

import org.springframework.stereotype.Repository;

import cn.xiangxu.telecom.login.entity.Admin;

@Repository("adminDao") // 利用注解创建一个属于该类的bean
public class AdminDaoJdbcImpl implements Serializable, AdminDao {
//	依赖注入连接池
	@Resource(name="dbcp")
	private DataSource ds;
	public Admin findByAdminCode(String adminCode) {
		Admin admin;
		Connection conn = null;
		try {
			conn = ds.getConnection();
			String sql = "SELECT * "
					+ "FROM admin_info "
					+ "WHERE admin_code = ? ";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, adminCode);
			
			ResultSet rs = ps.executeQuery();
			if(rs.next()) {
				admin = new Admin();
				admin.setAdminId(rs.getInt("admin_id"));
				admin.setAdminCode(rs.getString("admin_code"));
				admin.setPassword(rs.getString("password"));
				admin.setName(rs.getString("name"));
				admin.setTelephone(rs.getString("telephone"));
				admin.setEmail(rs.getString("email"));
				admin.setEnrolldate(rs.getTimestamp("enrolldate"));
				return admin;
			}
		} catch(SQLException e) {
//			出现异常的处理步骤：
//				step1:记录日志
			e.printStackTrace(); // 此处通过打印到控制台来记录日志
//				step2:判断捕获到的这个异常能否恢复，如果能就立即恢复，否则向上抛出
//					不能恢复的异常：数据库服务停止，一般称这样的一异常为系统异常
			throw new RuntimeException(e); // 此处选择向上抛出
		} finally {
			if(null != conn) {
				try {
					conn.close();
				} catch(SQLException e) {
					e.printStackTrace();
					throw new RuntimeException(e);
				}
			}
		}
		return null;
	}

}
